#include <QLineEdit>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QListWidget>
#include <QListWidgetItem>
#include <QPushButton>

#include "ItemStringList.h"

QStringList ItemStringList::get()
{
    return m_data;
}

void ItemStringList::set(const QStringList &value)
{
    m_data = value;
    emit itemEdited();
}

void ItemStringList::appendString(const QString &value)
{
    m_data.append(value);
    emit itemEdited();
}

QWidget *ItemStringList::createWidget(WidgetStyle s)
{
    Q_UNUSED(s)
    auto w = new QWidget;
    w->setMinimumWidth(250);
    auto vlayout = new QVBoxLayout(w);
    auto listWidget = new QListWidget;
    listWidget->setObjectName("listWidget");
    vlayout->addWidget(listWidget);

    auto hlayout = new QHBoxLayout;
    auto lineEdit = new QLineEdit;
    auto addBtn = new QPushButton;
    auto delBtn = new QPushButton;
    hlayout->addWidget(lineEdit);
    hlayout->addWidget(addBtn);
    hlayout->addWidget(delBtn);
    vlayout->addLayout(hlayout);

    addBtn->setText("添加");
    delBtn->setText("移除");

    connect(addBtn, &QPushButton::clicked, this, [=](){
        listWidget->addItem(lineEdit->text());
        emit onWidgetEditedWrapper();
    });

    connect(delBtn, &QPushButton::clicked, this, [=](){
        listWidget->takeItem(listWidget->currentRow());
        emit onWidgetEditedWrapper();
    });

    return w;
}

void ItemStringList::update(QWidget *widget, UpdateOption option)
{
    if (widget)
    {
        QListWidget *listWidget = widget->findChild<QListWidget*>("listWidget");
        if (option == UpdateOption::WidgetContent)
        {
            listWidget->clear();
            listWidget->addItems(m_data);
        }
        else if (option == UpdateOption::Item)
        {
            m_data.clear();
            for (int i = 0; i < listWidget->count(); i++)
            {
                QListWidgetItem *item = listWidget->item(i);
                m_data.append(item->text());
            }
        }
    }
}

void ItemStringList::writeToData(QDataStream &stream) const
{
    stream << m_data;
}

void ItemStringList::readFromData(QDataStream &stream)
{
    stream >> m_data;
    emit itemEdited();
}
